#pragma once


/**
 * 锁池
 */
template <typename LockObject>
class LockPool
{
public:
	LockPool();
	~LockPool();

	//初始化
	bool initialize(const unsigned long );

	//分配锁
	LockObject * allocate();

	void destory();

private:
	//锁数量
	unsigned long sizeByLock;

	//当前锁索引
	unsigned long index;

	//锁对象数组
	LockObject ** lockObj;

	//关闭复制
	LockPool(const LockPool &);

	LockPool &operator = (const LockPool &);
};

template <typename LockObject>
inline LockPool<LockObject>::LockPool() :sizeByLock(0), lockObj(NULL), index(0)
{

}

template <typename LockObject>
inline LockPool<LockObject>::~LockPool()
{

}

template<typename LockObject>
inline bool LockPool<LockObject>::initialize(const unsigned long lockNumber)
{
	this->sizeByLock = lockNumber;

	if (this->sizeByLock == 0)
	{
		SYSTEM_INFO sysInfo;

		GetSystemInfo(&sysInfo);

		//获取cpu核数初始化锁数量
		this->sizeByLock = sysInfo.dwNumberOfProcessors;
	}

	this->lockObj = new LockObject*[this->sizeByLock];

	for (unsigned long i = 0; i < this->sizeByLock; i++)
	{
		this->lockObj[i] = new LockObject();
	}

	this->index = 0;

	return true;
}

template <typename LockObject>
inline LockObject* LockPool<LockObject>::allocate()
{
	return this->lockObj[this->index % this->sizeByLock];
}

template <typename LockObject>
inline void LockPool<LockObject>::destory()
{
	if (this->sizeByLock <= 0 || this->lockObj < 0)
	{
		return;
	}

	for (unsigned long i = 0; i < this->sizeByLock; i++)
	{
		delete this->lockObj[i];
	}

	delete[] this->lockObj;

	this->index = this->sizeByLock = 0;
	
	this->lockObj = NULL;

}
